import numpy as np
import csv
from datetime import datetime


def load_data(file_path):
    """
    Load repository data and calculate activity metrics.
    Columns: repo_name, owner, stars, forks, language, created_at, last_commit, description.
    Returns: 2D NumPy array of shape (repos, 3) containing [stars, forks, active_days].
    """
    data = []

    with open(file_path, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        next(reader)

        for row in reader:
            repo_name, owner, stars, forks, language, created_at, last_commit, description = row
            stars = int(stars)
            forks = int(forks)

            created_at = datetime.strptime(created_at, "%Y-%m-%d")
            last_commit = datetime.strptime(last_commit, "%Y-%m-%d")

            active_days = (last_commit - created_at).days

            data.append([stars, forks, active_days])

    return np.array(data)


def calculate_statistics(data):
    """
    Calculate repository metrics statistics.
    Returns: Dictionary containing {
        'means': [stars_mean, forks_mean, days_mean],
        'medians': [stars_median, forks_median, days_median],
        'variances': [stars_var, forks_var, days_var],
        'stds': [stars_std, forks_std, days_std]
    }
    """
    means = np.mean(data, axis=0)
    medians = np.median(data, axis=0)
    variances = np.var(data, axis=0)
    stds = np.std(data, axis=0)

    return {
        'means': means,
        'medians': medians,
        'variances': variances,
        'stds': stds
    }


def print_results(stats):
    """
    Print formatted results with proper indentation.
    """
    metrics = ['Stars', 'Forks', 'Active Days']
    for metric, mean, med, var, std in zip(metrics,
                                           stats['means'],
                                           stats['medians'],
                                           stats['variances'],
                                           stats['stds']):
        print(f"{metric}:")
        print(f"    Average: {mean:.1f}")
        print(f"    Median: {med:.1f}")
        print(f"    Variance: {var:.1f}")
        print(f"    Standard Deviation: {std:.1f}")


repo_data = load_data('pakistan-repos.csv')
stats = calculate_statistics(repo_data)
print_results(stats)